#!/usr/bin/env python
# encoding:utf-8
'''
@author: yangyongjie
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. 
@contact: deamoncao100@gmail.com
software: garner
@file: user.py
@time: 2022/8/26 20:35
@desc:
'''
from wtforms import Form, StringField
from wtforms.validators import DataRequired, Email, Regexp, ValidationError
from model.user import UserManager
from werkzeug.security import check_password_hash

class UserForm(Form):
    #对客户端传递过来的username， email， password， phone进行校验
    #变量名需要和客户端传递的字段名一致
    username = StringField(validators=[DataRequired()])
    email = StringField(validators=[DataRequired(), Email(message="邮箱不合法")])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}', message="密码不符合要求")])
    phone_number = StringField(validators=[DataRequired(), Regexp(r'1\d{10}',message="电话不符合要求")])

    #自定义验证器，验证邮箱是否唯一
    #自定义检查字段 方法名：validate_你要检查的字段
    #value  客户端传递过来的email对象
    def validate_email(self, value):
        if UserManager.query.filter_by(email = value.data).first():
            raise ValidationError("邮箱已存在")

    def validate_username(self, value):
        #对数据进行修改，给客户端传进来的所有用户名都加一个sanchuang-开头
        value.data = "sanchuang-" + value.data

class LoginForm(Form):
    userName = StringField(validators=[DataRequired(), Email(message="邮箱不合法")])
    password = StringField(validators=[DataRequired(), Regexp(r'\w{6,18}', message="密码不符合要求")])

    def validate(self):
        super().validate()
        if self.errors:
            return False
        user = UserManager.query.filter_by(email =self.userName.data).first()
        if user and check_password_hash(user.password, self.password.data):
            return user
        else:
            raise ValidationError("验证失败！")